<template>
  <div class="inner-container">
    <div class="left-container">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="90px"
      >
        <TabelBox ref="tempData" :tabel-box-data="TabelBoxData" />
        <!-- -------------------------------------------- -->
        <div style="margin-top: 10px" />
        <el-form-item label="申请原因" prop="reason">
          <el-input
            v-model.trim="temp.reason"
            :disabled="flowStatus > 1"
            type="textarea"
            placeholder="请输入内容"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-row>
          <el-col :span="7">
            <el-form-item label="紧急程度" prop="urgent">
              <el-radio-group
                v-model="temp.urgent"
                :disabled="flowStatus > 1 || flowStatus == 0"
              >
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">紧急</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          v-if="flowStatus == 5 || flowStatus == 6"
          label="评审列表"
          prop="reason"
        >
          <el-tabs v-model="reviewPerson">
            <el-tab-pane
              v-for="item in reviewList"
              :key="item.name"
              :label="item.label"
              :name="item.name"
            >
              <span slot="label">
                <el-checkbox
                  v-model="item.content !== ''"
                  style="margin-right: 5px"
                />{{ item.label }}</span
              >
              {{ item.content }}
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <!-- ////////////////////////// -->
        <el-row>
          <el-form-item v-show="flowStatus == 1" label="审批人" prop="name">
            <el-tag
              v-for="(tag, index) in temp.reviewName"
              :key="index"
              :disable-transitions="false"
              class="tag"
            >
              {{ tag.userName }}
            </el-tag>
            <el-button
              size="mini"
              round
              circle
              icon="el-icon-plus"
              @click="openReview(3)"
            />
          </el-form-item>

          <el-form-item
            v-if="flowStatus == 2 && temp.result != 2"
            label="起草人"
            prop="name"
          >
            <el-tag
              v-for="(tag, index) in temp.reviewName"
              :key="index"
              :disable-transitions="false"
              class="tag"
            >
              {{ tag.userName }}
            </el-tag>
            <el-tooltip effect="dark" content="选择起草人" placement="top">
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(3)"
              />
            </el-tooltip>
          </el-form-item>
          <el-form-item v-show="flowStatus == 4" label="评审人" prop="name">
            <el-tag
              v-for="(tag, index) in temp.reviewName"
              :key="index"
              :disable-transitions="false"
              class="tag"
            >
              {{ tag.userName }}
            </el-tag>
            <el-tooltip effect="dark" content="选择评审人" placement="top">
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(4)"
              />
            </el-tooltip>
          </el-form-item>
          <!-- ------------------ -->
          <el-form-item
            v-show="flowStatus == 6 && reviewResult === 1"
            label="格式审核人"
            prop="name"
          >
            <el-tag
              v-for="(tag, index) in temp.reviewName"
              :key="index"
              :disable-transitions="false"
              class="tag"
            >
              {{ tag.userName }}
            </el-tag>
            <el-tooltip effect="dark" content="选择格式审核人" placement="top">
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(3)"
              />
            </el-tooltip>
            <el-tooltip effect="dark" content="添加评审人" placement="top">
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-sort"
                @click="updateReviewResult(2)"
              />
            </el-tooltip>
          </el-form-item>
          <el-form-item
            v-show="flowStatus == 6 && reviewResult === 2"
            label="评审人"
            prop="name"
          >
            <el-tag
              v-for="(tag, index) in temp.reviewName"
              :key="index"
              :disable-transitions="false"
              class="tag"
            >
              {{ tag.userName }}
            </el-tag>
            <el-tooltip effect="dark" content="选择评审人" placement="top">
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(4)"
              />
            </el-tooltip>
            <el-tooltip effect="dark" content="格式审核" placement="top">
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-sort"
                @click="updateReviewResult(1)"
              />
            </el-tooltip>
          </el-form-item>
          <!-- ---------------- -->
          <!-- <el-form-item v-show="flowStatus == 7" label="文件审核人" prop="name">
            <el-tag
              v-for="(tag, index) in temp.reviewName"
              :key="index"
              :disable-transitions="false"
              class="tag"
            >
              {{ tag.userName }}
            </el-tag>
            <el-tooltip effect="dark" content="选择文件审核人" placement="top">
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(3)"
              />
            </el-tooltip>
          </el-form-item> -->
          <el-form-item v-show="flowStatus == 8" label="批准人" prop="name">
            <el-tag
              v-for="(tag, index) in temp.reviewName"
              :key="index"
              :disable-transitions="false"
              class="tag"
            >
              {{ tag.userName }}
            </el-tag>
            <el-tooltip effect="dark" content="选择批准人" placement="top">
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(3)"
              />
            </el-tooltip>
          </el-form-item>
          <el-form-item v-show="flowStatus == 9" label="文件管理员" prop="name">
            <el-tag
              v-for="(tag, index) in temp.reviewName"
              :key="index"
              :disable-transitions="false"
              class="tag"
            >
              {{ tag.userName }}
            </el-tag>
            <el-tooltip effect="dark" content="选择文件管理员" placement="top">
              <el-button
                size="mini"
                round
                circle
                icon="el-icon-plus"
                @click="openReview(3)"
              />
            </el-tooltip>
          </el-form-item>
          <div v-if="flowStatus == 7">
            <el-form-item label="文件审核人" prop="name">
              <el-tag
                v-for="(tag, index) in savePhaseName['audit']"
                :key="index"
                :disable-transitions="false"
                class="tag"
              >
                {{ tag.userName }}
              </el-tag>
              <el-tooltip
                effect="dark"
                content="选择文件审核人"
                placement="top"
              >
                <el-button
                  size="mini"
                  round
                  circle
                  icon="el-icon-plus"
                  @click="openReview(3, 'audit')"
                />
              </el-tooltip>
            </el-form-item>

            <el-form-item label="批准人" prop="name">
              <el-tag
                v-for="(tag, index) in savePhaseName['approve']"
                :key="index"
                :disable-transitions="false"
                class="tag"
              >
                {{ tag.userName }}
              </el-tag>
              <el-tooltip effect="dark" content="选择批准人" placement="top">
                <el-button
                  size="mini"
                  round
                  circle
                  icon="el-icon-plus"
                  @click="openReview(3, 'approve')"
                />
              </el-tooltip>
            </el-form-item>

            <el-form-item label="文件管理员" prop="name">
              <el-tag
                v-for="(tag, index) in savePhaseName['release']"
                :key="index"
                :disable-transitions="false"
                class="tag"
              >
                {{ tag.userName }}
              </el-tag>
              <el-tooltip effect="dark" content="选择批准人" placement="top">
                <el-button
                  size="mini"
                  round
                  circle
                  icon="el-icon-plus"
                  @click="openReview(3, 'release')"
                />
              </el-tooltip>
            </el-form-item>
          </div>
          <el-form-item
            v-show="
              (flowStatus > 1 && flowStatus != 3 && reviewResult === 1) ||
              flowStatus == 0
            "
            label="处理意见"
          >
            <el-input
              v-model.trim="temp.opinion"
              maxlength="200"
              type="textarea"
            />
          </el-form-item>

          <el-form-item
            v-if="
              flowStatus == 2 ||
              flowStatus == 9 ||
              flowStatus == 7 ||
              flowStatus == 8
            "
            label="处理结果"
          >
            <el-radio-group v-model="temp.result">
              <el-radio :label="1">通过</el-radio>
              <el-radio :label="2">拒绝</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <!-- ssssssssssssssssssssssssss -->
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="flowStatus == 10" label="发放部门" prop="name">
              <el-tag
                v-for="(tag, index) in receiveUserGroupList"
                :key="index"
                :disable-transitions="false"
                style="margin-right: 10px"
                @close="handleCloseTagGroup(tag)"
              >
                {{ tag.label }}
              </el-tag>
              <el-tooltip effect="dark" content="选择部门" placement="top">
                <el-button
                  size="mini"
                  round
                  circle
                  icon="el-icon-plus"
                  @click="openReview(5)"
                />
              </el-tooltip>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="flowStatus == 10" label="发放人员" prop="name">
              <el-tag
                v-for="(tag, index) in temp.reviewName"
                :key="index"
                :disable-transitions="false"
                style="margin-right: 10px"
                @close="handleCloseTag(tag)"
              >
                {{ tag.userName }}
              </el-tag>
              <el-tooltip effect="dark" content="选择人员" placement="top">
                <el-button
                  size="mini"
                  round
                  circle
                  icon="el-icon-plus"
                  @click="openReview(4)"
                />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item v-if="flowStatus == 10" label="生效日期" prop="name">
          <el-date-picker
            v-model="temp.effectDate"
            type="date"
            :picker-options="pickerOptions"
            value-format="yyyy-MM-dd"
            placeholder="选择日期时间"
          />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-if="flowStatus == 10"
              label="是否培训"
              prop="trainFlag"
            >
              <el-radio
                v-model="temp.trainFlag"
                :label="false"
                @change="trainFlagRadio"
                >否</el-radio
              >
              <el-radio
                v-model="temp.trainFlag"
                :label="true"
                @change="trainFlagRadio"
                >是</el-radio
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="temp.trainFlag == 1"
              label="培训讲师"
              prop="name"
            >
              <el-tag v-if="trainName">{{ trainName }}</el-tag>
              <el-tooltip effect="dark" content="选择讲师" placement="top">
                <el-button
                  size="mini"
                  round
                  circle
                  icon="el-icon-plus"
                  @click="openReview(3)"
                />
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12" v-if="withSafeMode === 'false'">
            <el-form-item
              v-if="flowStatus == 9 && withSafeMode"
              label="体系体现"
            >
              <el-radio v-model="temp.withSafeMode" label="false">否</el-radio>
              <el-radio v-model="temp.withSafeMode" label="true">是</el-radio>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-form-item>
          <el-button
            v-if="reviewResult === 1"
            size="small"
            type="primary"
            icon="el-icon-top button-icon"
            @click="handleSubmit"
            >提交</el-button
          >
          <el-button
            v-if="reviewResult === 2"
            size="small"
            icon="el-icon-top button-icon"
            @click="handleSubmit"
            >增加评审人</el-button
          >
          <el-button
            v-if="flowStatus == 9"
            size="small"
            icon="el-icon-close button-icon"
            @click="handleClose"
            >终止流程</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="right-container">
      <TimeLine :timeline-data="TimelineData" />
    </div>
    <div />

    <div>
      <SearchPersonnelType
        :search-personnel-type-data="SearchPersonnelTypeData"
        @dataList="dataList"
      />
      <SearchPersonnel
        :search-personnel-data="SearchPersonnelData"
        @dataListData="dataListData"
      />
      <SearchUserList
        :search-user-list-data="SearchUserListData"
        @SearchUserList="SearchUserList"
      />
      <SelectGroupList
        :select-group-list-data="SelectGroupListData"
        @UserGroupListData="UserGroupListData"
      />
    </div>
  </div>
</template>

<script>
import {
  apply,
  upload,
  edit,
  review,
  editAgain,
  formatAudit,
  contentAudit,
  approval,
  release,
  applyApproval
} from '@/api/xd/flow/flow_new'
import {
  getDocumentFlowNewAndModify,
  nodeHandle,
  nodesHandle,
  Termination,
  assigneeDocumentFlow,
  saveHandleUser,
  listHandleUser
} from '@/api/xd/documentFlow'
// import { getUserName } from '@/api/uc/user'
import { getBranchList } from '@/api/uc/search'
import { mapGetters } from 'vuex'
import { get, set } from '@/utils/db'

import SearchPersonnelType from '@/components/SearchUserType/index.vue'
import SearchPersonnel from '@/components/SearchUser/SearchPersonnel.vue'
import SearchUserList from '@/components/SearchUserList/index'
import SelectGroupList from '@/components/SelectGroupList/index.vue'
import TimeLine from '@/views/flow/components/Timeline'
import TabelBox from '../components/newTableBox'
import { listItemByParent } from '@/api/base/dict.js'
// import { parse } from 'path-to-regexp'

export default {
  components: {
    SearchPersonnelType,
    SearchPersonnel,
    SearchUserList,
    SelectGroupList,
    TimeLine,
    TabelBox
  },
  computed: {
    ...mapGetters(['roles'])
  },
  data() {
    const FLOW_TYPE_NEW = 1
    const PHASE_APPLY = 1
    const PHASE_APPLY_APPROVAL = 2
    const PHASE_UPLOAD = 3
    const PHASE_EDIT = 4
    const PHASE_REVIEW = 5
    const PHASE_EDIT_AGAIN = 6
    const PHASE_FORMAT_AUDIT = 7
    const PHASE_CONTENT_AUDIT = 8
    const PHASE_APPROVAL = 9
    const PHASE_RELEASE = 10
    return {
      title: '',
      reviewPerson: '',
      reviewList: [],
      visible: false,
      documentRealName: '',
      flowStatus: PHASE_APPLY,
      withSafeMode: process.env.VUE_APP_WITHSAFEMODE,
      flowStatusOptions: [
        {
          value: PHASE_APPLY,
          phaseName: '新增申请',
          phase: 'newApply',
          color: '#adaaa5'
        },
        {
          value: PHASE_APPLY_APPROVAL,
          phaseName: '流程审批',
          phase: 'applyApproval'
        },
        // { value: PHASE_UPLOAD, phaseName: '上传模板', phase: 'adminAudit' },
        { value: PHASE_EDIT, phaseName: '文件编辑', phase: 'draft' },
        { value: PHASE_REVIEW, phaseName: '文件评审', phase: 'review' },
        { value: PHASE_EDIT_AGAIN, phaseName: '再次编辑', phase: 'revise' },
        {
          value: PHASE_FORMAT_AUDIT,
          phaseName: '格式审核',
          phase: 'format_audit'
        },
        { value: PHASE_CONTENT_AUDIT, phaseName: '文件审核', phase: 'audit' },
        { value: PHASE_APPROVAL, phaseName: '文件审批', phase: 'approve' },
        { value: PHASE_RELEASE, phaseName: '新增发行', phase: 'release' }
      ],
      DocumentVersionData: 'sss',
      temp: {
        flowType: FLOW_TYPE_NEW,
        documentName: null,
        urgent: '0',
        documentCode: '',
        documentVersion: 'A0',
        reason: null,
        documentId: null,
        documentManagerUserId: 1,
        documentManagerUserGroupId: 1,
        result: 1,
        reviewName: [],
        reviewId: '',
        withSafeMode: true
      },
      rules: {},
      activities: [],
      userGroup: [],
      userGroupId: '',
      repository: [],
      repositoryId: '',
      options: [],
      refresh: 0,
      dialogReview: false,
      reviewData: [],
      reviewWindow: 0,
      folderId: '0',
      fileList: '',
      reviewNameList: [],
      reviewUserId: [],
      headList: [],
      receiveUserGroupIdList: [],
      receiveUserGroupList: [],
      levels: [],
      categories: [],

      SearchPersonnelTypeData: {},
      dialogVisible: false,
      SearchPersonnelData: {},
      SearchUserListData: {},
      SelectGroupListData: {},
      trainName: '',
      pattern: '',
      TimelineData: {},
      tempName: [],
      fileExtension: '',
      // 禁用当前日期之前的日期
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      TabelBoxData: {},
      tempData: null,
      savePhaseName: {
        applyApproval: [],
        review: [],
        format_audit: [],
        audit: [],
        approve: [],
        release: []
      },
      phaseIndex: null,
      reviewResult: 1
    }
  },
  watch: {
    options() {
      ++this.refresh
    },
    pattern(data) {
      this.pattern = data
    },
    'temp.category'(data) {
      if (data.indexOf('JL') != -1) {
        this.DocumentVersionData = {
          type: '1'
        }
      } else {
        this.DocumentVersionData = {
          type: '0'
        }
      }
    },
    'temp.level'(data) {
      // console.log(data, 'iiiiii')
    }
  },
  created() {
    this.pattern = this.$route.query.type
    if (this.$route.query.phase) {
      this.flowStatus = Number(this.$route.query.phase)
    }
    if (
      this.$route.params.documentFlowId &&
      this.$route.params.documentFlowId != 0
    ) {
      this.getFlowData(this.$route.params.documentFlowId)
      if (this.flowStatus === 5) {
        this.getReview(this.$route.params.documentFlowId)
      }
      if (this.flowStatus === 6) {
        this.getStatusReviewData(this.$route.params.documentFlowId)
      }
    }

    this.getNodeShanDle()
  },
  mounted() {
    this.toTabelBoxData()
    this.TimelineFun()
    this.updateTemp()
    this.getListHandleUser()
  },
  updated() {
    this.$emit('flowData', {
      flowStatus: this.flowStatus,
      documentCode: this.temp.documentCode
    })
  },
  beforeUpdate() {
    this.TimelineFun()
  },

  methods: {
    async updateTemp() {
      if (this.flowStatus < 7) {
        const newTempList = await this.getDfaultUser()
        let newTemp = null
        if (this.flowStatus !== 4) {
          newTemp = await this.setReviewList(newTempList, 0)
        } else {
          newTemp = await this.setReviewList(newTempList, 1)
        }

        this.temp = JSON.parse(JSON.stringify(newTemp))
      }
    },
    getListHandleUser() {
      const phase = {
        6: 'format_audit',
        7: 'audit',
        8: 'approve'
      }
      const data = {
        documentFlowId: this.$route.params.documentFlowId,
        phase: phase[this.flowStatus]
      }
      if (this.flowStatus === 8 || this.flowStatus === 9) {
        listHandleUser(data).then((res) => {
          const { data } = res
          this.temp.reviewId = data[data.length - 1].handleUserId
          const nameList = [
            {
              userName: data[data.length - 1].handleUserName,
              userId: data[data.length - 1].handleUserId
            }
          ]
          this.temp.reviewName = nameList
          this.$forceUpdate()
        })
      }
    },
    // 表格数据
    toTabelBoxData() {
      this.TabelBoxData = {
        flowStatus: this.flowStatus,
        roles: this.roles,
        temp: []
      }
    },
    // 时间线数据
    TimelineFun() {
      this.TimelineData = {
        documentFlowId: this.temp.documentFlowId,
        status: this.temp,
        flowStatusOptions: this.flowStatusOptions
      }
    },
    inputData(val) {
      this.temp.documentVersion = val
    },

    handleLevelChange(val) {
      for (let i = 0, len = this.levels.length; i < len; i++) {
        if (this.levels[i].value === val) {
          this.categories = this.levels[i].children
          if (this.temp.category) {
            this.temp.category = ''
          }
        }
      }
    },
    async getStatusReviewData(documentFlowId) {
      const data = {
        documentFlowId: documentFlowId,
        phase: 'review'
      }
      nodeHandle(data).then((res) => {
        if (res.data.length > 0) {
          this.reviewList = []
          res.data.forEach((item) => {
            this.reviewList.push({
              name: item.handleUserId,
              label: item.handleUserName,
              content: item.opinion
            })
          })
          this.reviewPerson = this.reviewList[0].name
        }
      })
    },
    async getReview(documentFlowId) {
      const data = {
        documentFlowId: documentFlowId,
        phase: 'review'
      }
      const list = []
      nodeHandle(data).then((res) => {
        if (res.data.length > 0) {
          res.data.forEach((item) => {
            list.push({
              name: item.handleUserId,
              label: item.handleUserName,
              content: item.opinion
            })
          })
        }
      })
      let reviewList = null
      reviewList = await assigneeDocumentFlow(data)
      if (list.length > 0) {
        reviewList.data.forEach((item) => {
          list.forEach((e, index) => {
            if (e.name !== item.userId) {
              list.push({
                content: '',
                label: item.userName,
                name: item.userId
              })
            } else {
              list.splice(index, 1)
            }
          })
        })
        this.reviewList = [...this.reviewList, ...list]
      } else {
        reviewList.data.forEach((item) => {
          this.reviewList.push({
            content: '',
            label: item.userName,
            name: item.userId,
            handleUserId: item.userId
          })
        })
      }
      this.reviewPerson = this.reviewList[0].name
    },
    // 拒绝驳回
    reject(lab) {
      console.log('3333333333333')
      if (lab == 1) {
        this.temp.result = 2
      } else {
        this.temp.result = 1
      }
      console.log(this.temp.result)
      this.$forceUpdate()
    },

    openDocument(val) {
      if (this.fileExtension.indexOf('.pdf') != -1) {
        window.open(
          process.env.VUE_APP_BASE_API +
            '/api/fd/pdf/get_document_by_pdf?documentId=' +
            this.temp.documentId
        )
      } else {
        window.open(
          'onlyoffice/createDocument.html?&token=' +
            this.$store.getters.token +
            '&documentId=' +
            this.temp.documentId +
            '&mode=' +
            val +
            '&urldata=' +
            process.env.VUE_APP_BASE_API
        )
      }
    },
    //
    getFlowData(documentFlowId) {
      getDocumentFlowNewAndModify({ documentFlowId: documentFlowId }).then(
        (res) => {
          let data = {}
          data = res.data
          data.result = 1
          data.level = res.data.documentLevel
          data.category = res.data.documentProperty
          this.TabelBoxData = {
            flowStatus: this.flowStatus,
            roles: this.roles,
            temp: res.data.documentFlowInfoList
          }
          this.temp = Object.assign(data)
          if (this.flowStatus === 3) {
            this.temp.reviewId = this.temp.createUserId
          }
          // 第二步文件上传默认的编辑人回显
          const ids = []
          this.temp.documentFlowInfoList.forEach((e) => {
            ids.push(e.documentId)
          })

          if (this.flowStatus === 10) {
            // this.setGroupAnUserList()
            this.temp.withSafeMode = process.env.VUE_APP_WITHSAFEMODE
            this.withSafeMode = process.env.VUE_APP_WITHSAFEMODE
          }
        }
      )
    },
    // 获取流程默认人
    async getDfaultUser() {
      const data = {
        dictGroupCode: 'flow_default_handle_user',
        dictCode: this.flowStatusOptions[this.flowStatus].phase,
        parentDictCode: '1'
      }
      let row = {}
      row = await listItemByParent(data)
      row = this.redoUsreList(row.data)
      return row
    },
    redoUsreList(data) {
      data.forEach((e) => {
        e.userName = e.dictValue
      })
      return data
    },
    setReviewList(row, type) {
      const data = row || []
      const userList = []
      const newData = this.temp
      if (data.length > 0) {
        if (type === 0) {
          userList.push(data[data.length - 1])
          newData.reviewName = userList
          newData.reviewId = data[data.length - 1].dictCode
        } else {
          newData.reviewName = data
          const idList = []
          data.forEach((e) => {
            idList.push(e.dictCode)
          })
          this.reviewUserId = idList
        }
      }
      return newData
    },

    setGroupAnUserList() {
      const userList = JSON.parse(get('newReleaseReviewUserList'))
      const GroupList = JSON.parse(get('newReleaseReviewGroupList'))
      const userListId = JSON.parse(get('newReleaseReviewUserListId'))
      const groupLiatId = JSON.parse(get('newReleaseReviewGroupListId'))
      this.temp.reviewName = userList || []
      this.receiveUserGroupList = GroupList || []
      this.reviewUserId = userListId || []
      this.receiveUserGroupIdList = groupLiatId || []
    },

    trainFlagRadio(val) {
      if (val == 0) {
        this.temp.reviewId = null
        this.temp.reviewName = null
      }
    },
    /**
     * 共两个参数，依次为：传递给 data 属性的数组中该节点所对应的对象、树目前的选中状态对象，
     * 包含 checkedNodes、checkedKeys、halfCheckedNodes、halfCheckedKeys 四个属性
     */
    // 操作发放人员tag标签
    handleCloseTag(tag) {
      this.temp.reviewName.splice(this.temp.reviewName.indexOf(tag), 1)
      this.reviewUserId.splice(this.reviewUserId.indexOf(tag), 1)
      this.$forceUpdate()
    },
    // 发放部门
    handleCloseTagGroup(tag) {
      this.receiveUserGroupList.splice(
        this.receiveUserGroupList.indexOf(tag),
        1
      )
      this.receiveUserGroupIdList.splice(
        this.receiveUserGroupIdList.indexOf(tag),
        1
      )
    },
    handleCheckChange(obj, objs) {
      // 如果状态为三，则为多选
      if (this.flowStatus === 4) {
        this.temp.reviewId = obj.id
      }
      // 人员默认的
      if (this.reviewWindow === 0) {
        this.temp.reviewId = obj.id
        this.temp.reviewName = obj.label
      }
      // 选择多个人员的
      if (this.reviewWindow === 1) {
        this.temp.receiveUserIdList = obj.id
      }
      // 选择多个部门
      if (this.reviewWindow === 2) {
        this.temp.receiveUserGroupIdList = obj.id
      }
    },
    // 部门获取
    async getBranchList() {
      this.headList = await getBranchList()
    },

    closeDialog() {
      this.userGroup = []
      this.userGroupId = ''
      this.repository = []
      this.repositoryId = ''
      this.options = []
    },

    getDocument(val) {
      const arr = this.$refs['cascaderDocuemtn'].getCheckedNodes()[0].pathLabels
      this.temp.documentIdCopy = val[arr.length - 1]
    },
    setFolder(val) {
      const obj = this.$refs['cascadeDocument'].getCheckedNodes()[0]
      this.temp.folderId = obj.value
    },

    compare() {},
    handleTaskPage() {},
    async handleSubmit() {
      if (this.flowStatus === 1) {
        const res = await this.$refs['tempData'].backTempData()

        let documentFlowInfoList = []
        if (res.valid) {
          documentFlowInfoList = Array.from(res.documentFlowInfoList)
          documentFlowInfoList.forEach((e) => {
            delete e.modeDocumentName
          })
        } else {
          return
        }
        let batchType = 0
        if (documentFlowInfoList.length > 1) {
          batchType = 2
        }
        // 申请
        const data = {
          documentManagerUserId: this.temp.reviewId,
          reason: this.temp.reason,
          urgent: this.temp.urgent,
          documentFlowInfoList: documentFlowInfoList,
          batchType: batchType
        }
        documentFlowInfoList.forEach((e) => {
          let isDocumentId = false
          if (e.documentId === null) {
            this.$message.warning(e.documentCode + '未设置模板文件')
            isDocumentId = true
            throw new Error('LoopInterrupt')
          }
          if (isDocumentId) {
            return
          }
        })
        if (!data.reason) {
          this.$message.warning('申请原因不可为空')
          return
        }
        if (!data.documentManagerUserId) {
          this.$message.warning('审批人不可为空')
          return
        }
        apply(data).then((res) => {
          this.$message.success('操作成功')
          this.$router.push('/unread')
        })
      }
      // 流程审批
      if (this.flowStatus === 2) {
        if (this.temp.result == 2) {
          this.temp.result = 3
        }
        const data = {
          documentFlowId: this.temp.documentFlowId,
          nextHandleUserId: this.temp.reviewId,
          result: this.temp.result,
          opinion: this.temp.opinion
        }
        if (data.result == null) {
          this.$message.warning('处理结果不可为空')
          return
        }
        if (data.result == 1) {
          if (!data.nextHandleUserId) {
            this.$message.warning('文件管理员不可为空')
            return
          }
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }
        applyApproval(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit('message/FLOW_COUNT', 2)
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 3) {
        if (this.temp.result == 2) {
          this.temp.result = 3
        }
        await this.$refs['tempData'].backResult(this.temp.result)
        const res = await this.$refs['tempData'].backTempData()
        let documentFlowInfoList = []
        if (res.valid) {
          documentFlowInfoList = Array.from(res.documentFlowInfoList)
          documentFlowInfoList.forEach((e) => {
            delete e.modeDocumentName
          })
        } else {
          if (this.temp.result !== 3) {
            return
          }
        }

        const data = {
          documentFlowId: this.temp.documentFlowId,
          documentFlowInfoList: documentFlowInfoList || [],
          editUserId: this.temp.reviewId,
          result: this.temp.result,
          opinion: this.temp.opinion
        }
        if (data.result == null) {
          this.$message.warning('处理结果不可为空')
          return
        }
        if (data.result == 1) {
          if (!data.editUserId) {
            this.$message.warning('起草人员不可为空')
            return
          }
        }
        upload(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit(
            'message/FLOW_COUNT',
            this.$store.state.message.flowCount - 1
          )
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 4) {
        // 编辑
        const data = {
          documentFlowId: this.temp.documentFlowId,
          opinion: this.temp.opinion,
          reviewUserIdList: this.reviewUserId
        }
        set(
          'reviewUserList',
          JSON.stringify({
            reviewUserId: this.reviewUserId,
            reviewName: this.temp.reviewName
          })
        )

        if (data.reviewUserIdList.length == 0) {
          this.$message.warning('评审人不可为空')
          return
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }
        edit(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit(
            'message/FLOW_COUNT',
            this.$store.state.message.flowCount - 1
          )
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 5) {
        // 评审
        const data = {
          documentFlowId: this.temp.documentFlowId,
          opinion: this.temp.opinion
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }
        review(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit(
            'message/FLOW_COUNT',
            this.$store.state.message.flowCount - 1
          )
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 6) {
        console.log(this.temp.reviewId, 'this.temp.reviewId')
        // 再次编辑
        let data = {}
        if (this.reviewResult === 1) {
          data = {
            documentFlowId: this.temp.documentFlowId,
            opinion: this.temp.opinion,
            auditUserId: this.temp.reviewId
            // auditUserId: this.savePhaseName.format_audit[0].userId
          }
          if (!data.auditUserId) {
            this.$message.warning('格式审核人不可为空')
            return
          }
          if (!data.opinion) {
            this.$message.warning('处理意见不可为空')
            return
          }
        } else {
          data = {
            documentFlowId: this.temp.documentFlowId,
            reviewUserIdList: this.reviewUserId,
            result: this.reviewResult
          }
          if (data.reviewUserIdList.length <= 0) {
            this.$message.warning('评审人不可为空')
            return
          }
        }
        editAgain(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit(
            'message/FLOW_COUNT',
            this.$store.state.message.flowCount - 1
          )
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 7) {
        // 格式审核
        const data = {
          documentFlowId: this.temp.documentFlowId,
          // nextHandleUserId: this.temp.reviewId,
          nextHandleUserId: this.savePhaseName.audit[0].userId,

          opinion: this.temp.opinion,
          result: this.temp.result
        }
        if (data.result == null) {
          this.$message.warning('处理结果不可为空')
          return
        }
        if (data.result == 1) {
          if (!data.nextHandleUserId) {
            this.$message.warning('审核人不可为空')
            return
          }
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }
        this.builtHandleUser(data.documentFlowId, this.savePhaseName)
        formatAudit(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit(
            'message/FLOW_COUNT',
            this.$store.state.message.flowCount - 1
          )
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 8) {
        // 内容审核
        const data = {
          documentFlowId: this.temp.documentFlowId,
          nextHandleUserId: this.temp.reviewId,
          opinion: this.temp.opinion,
          result: this.temp.result
        }
        if (data.result == null) {
          this.$message.warning('处理结果不可为空')
          return
        }
        if (data.result == 1) {
          if (!data.nextHandleUserId) {
            this.$message.warning('批准人不可为空')
            return
          }
        } else {
          if (!data.opinion) {
            this.$message.warning('处理意见不可为空')
            return
          }
        }

        contentAudit(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit(
            'message/FLOW_COUNT',
            this.$store.state.message.flowCount - 1
          )
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 9) {
        // 审批
        const data = {
          documentFlowId: this.temp.documentFlowId,
          nextHandleUserId: this.temp.reviewId,
          opinion: this.temp.opinion,
          result: this.temp.result
        }
        console.log(this.temp.result, 'this.temp.result')
        if (data.result == null) {
          this.$message.warning('处理结果不可为空')
          return
        }
        if (data.result == 1) {
          if (!data.nextHandleUserId) {
            this.$message.warning('文件管理员不可为空')
            return
          }
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }
        approval(data).then(() => {
          this.$message.success('操作成功')
          this.$store.commit(
            'message/FLOW_COUNT',
            this.$store.state.message.flowCount - 1
          )
          this.$router.push('/unread')
        })
      }
      if (this.flowStatus === 10) {
        console.log(
          this.reviewUserId,
          this.receiveUserGroupIdList,
          'this.receiveUserGroupIdList'
        )
        // 放行
        const data = {
          documentFlowId: this.temp.documentFlowId,
          effectDate: this.temp.effectDate,
          opinion: this.temp.opinion,
          receiveUserGroupIdList:
            this.receiveUserGroupIdList != null
              ? this.receiveUserGroupIdList
              : null,
          receiveUserIdList:
            this.reviewUserId != null ? this.reviewUserId : null,
          //
          trainFlag: this.temp.trainFlag,
          trainerUserId: this.temp.reviewId,
          safeMode: false
        }
        if (
          data.receiveUserGroupIdList.length == 0 &&
          data.receiveUserIdList.length == 0
        ) {
          this.$message.warning('发行的目标不可为空')
          return
        }
        if (!data.opinion) {
          this.$message.warning('处理意见不可为空')
          return
        }
        if (!data.effectDate) {
          this.$message.warning('发行时间不可为空')
          return
        }
        if (data.trainFlag == null) {
          this.$message.warning('  参加培训不可为空')
          return
        }
        if (data.trainFlag) {
          if (!data.trainerUserId) {
            this.$message.warning('培训人不可为空')
            return
          }
        }
        set('newReleaseReviewUserList', JSON.stringify(this.temp.reviewName))
        set('newReleaseReviewUserListId', JSON.stringify(this.reviewUserId))
        set(
          'newReleaseReviewGroupList',
          JSON.stringify(this.receiveUserGroupList)
        )
        set(
          'newReleaseReviewGroupListId',
          JSON.stringify(this.receiveUserGroupIdList)
        )
        release(data).then(() => {
          this.$message.success('操作成功')
          this.$router.push('/unread')
        })
      }
    },
    handleStop() {},
    handleClose() {
      this.$confirm('此操作将终止该流程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          Termination({
            documentFlowId: this.$route.params.documentFlowId
          }).then((res) => {
            if (res.code == 1) {
              this.$message.success('终止流程成功')
            }
          })
          this.$router.push({ path: '/unread' })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //
    //
    // 时间线
    async getNodeShanDle() {
      const nodeShanDleData =
        (await nodesHandle({
          documentFlowId: this.temp.documentFlowId
        })) || []
      nodeShanDleData.data.forEach((item) => {
        for (const key in this.activities) {
          if (item.phase == this.activities[key].phase) {
            Object.assign(this.activities[key], item)
          }
        }
      })
    },
    // 人员优化》》》》》》》》》》》》》》》》》》》》》》
    openReview(val, phase) {
      // 0为角色 1为角色（总经理，总监） 3为架构 4为架构多选 5部门多选
      this.reviewWindow = val
      // if (val == 0) {
      //   this.SearchPersonnelTypeData = {
      //     val: val,
      //     type: type,
      //     dialogVisible: true,
      //     title: title,
      //     temp: this.temp
      //   }
      // } else if (val == 1) {
      //   if (
      //     this.temp.documentLevelNum == 1 ||
      //     this.temp.documentLevelNum == 2
      //   ) {
      //     type = 'president'
      //     title = '总经理'
      //   } else {
      //     type = 'director'
      //     title = '总监'
      //   }
      //   this.SearchPersonnelTypeData = {
      //     val: val,
      //     type: type,
      //     dialogVisible: true,
      //     title: title
      //   }
      // } else
      if (val === 3) {
        this.SearchPersonnelData = {
          dialogVisible: true
        }
        this.phaseIndex = phase
      } else if (val === 4) {
        this.SearchUserListData = {
          dialogVisible: true
        }
        this.phaseIndex = phase
      }
      else if (val == 5) {
        this.SelectGroupListData = {
          dialogVisible: true
        }
      }
    },
    dataList(val) {
      if (this.flowStatus === 10) {
        this.trainName = val[0].userName
        this.temp.reviewId = val[0].userId
      } else {
        this.temp.reviewName = val
        if (val[0].userId) {
          this.temp.reviewId = val[0].userId
        }
      }

      this.$forceUpdate()
    },
    // 》》》》》》》》》》》》》》》》》》》》》》》》》》
    // 优化流程所有人员
    dataListData(row) {
      const data = row || []

      const dataList = []
      data.forEach((res) => {
        dataList.push({ userName: res.label, userId: res.id })
      })

      if (this.flowStatus !== 7) {
        if (this.temp.trainFlag) {
          this.trainName = data[0].label
          this.temp.reviewId = data[0].id
          return
        }
        this.temp.reviewName = dataList
        this.temp.reviewId = data[0].id
        this.$forceUpdate()
      } else {
        this.savePhaseName[this.phaseIndex] = dataList
        this.$forceUpdate()
      }
    },
    SearchUserList(row) {
      const data = row || []
      const newData = []
      const idList = []
      data.map((item, index) => {
        idList.push(item.id)
        newData.push({
          id: item.id,
          userName: item.label
        })
      })
      this.reviewUserId = idList
      this.temp.reviewName = newData
      this.$forceUpdate()
    },
    UserGroupListData(data) {
      this.receiveUserGroupList = []
      this.receiveUserGroupIdList = []
      this.receiveUserGroupList = data
      data.map((item) => {
        this.receiveUserGroupIdList.push(item.id)
      })
    },
    builtHandleUser(documentFlowId, data) {
      const list = []
      for (let key in data) {
        data[key].forEach((e) => {
          const data = {
            documentFlowId: documentFlowId,
            phase: key,
            handleUserId: e.userId || e.id
          }
          list.push(data)
        })
      }
      saveHandleUser(list)
    },
    updateReviewResult(index) {
      this.reviewResult = index
      this.temp.reviewName = []
      this.temp.reviewId = null
    }
  }
}
</script>

<style lang="scss" scoped>
//
.buttonleft {
  margin-left: 85%;
}
.buttonup {
  margin-right: 10px;
  font-size: 12px;
  padding: 10px 20px;
}
.inline-block {
  display: inline-block;
}
.tag {
  margin-left: 10px;
}
.active {
  display: none;
}
.inner-container {
  display: -webkit-flex;
  display: flex;
  flex-direction: row;
}

.left-container {
  width: calc(100% - 300px);
}

.right-container {
  width: 400px;
  .el-timeline {
    .el-timeline-item {
      height: 56px;
      line-height: 56px;

      p {
        height: 16px;
        line-height: 16px;
        font-size: 13px;
      }
    }
  }
}
</style>
